﻿/* 
 * Copyright 2010 Justin Pealing
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

using System;
using System.IO;
using Minnow.Web.Http;

namespace Minnow.Web
{
    /// <summary>
    /// Responds to http requests.
    /// </summary>
    /// <remarks>
    /// A handler should only service requests for a single server.
    /// </remarks>
    public abstract class RequestHandler
    {
        /// <summary>
        /// Gets the path to the local directory that the server requests map onto.
        /// </summary>
        protected string LocalRoot
        {
            get
            {
                return this.localRoot;
            }
        }
        private string localRoot;

        /// <summary>
        /// Gets the root Url from which requests are mapped
        /// </summary>
        protected string RootUrl
        {
            get
            {
                return this.rootUrl;
            }
        }
        private string rootUrl;

        /// <summary>
        /// Initialises the handler, preparing it to accept Http requests.
        /// </summary>
        /// <param name="LocalRoot">The path to the local directory that the server requests map onto.</param>
        /// <param name="RootUrl">The root Url from which requests are mapped.</param>
        public virtual void Initialise(string LocalRoot, string RootUrl)
        {
            if (string.IsNullOrEmpty(LocalRoot))
            {
                throw new InvalidOperationException("You must specify a RootDirectory");
            }
            if (!Directory.Exists(LocalRoot))
            {
                throw new InvalidOperationException("The RootDirectory specified does not exist");
            }

            this.localRoot = LocalRoot;
            this.rootUrl = RootUrl;
        }

        /// <summary>
        /// Handles a http request.
        /// </summary>
        /// <param name="FilePath">Path to the local file, or null if no corresponding local file mapping exists.</param>
        /// <param name="Request">Request object.</param>
        /// <param name="Response">Response object.</param>
        public abstract void Process(IHttpRequest Request, IHttpResponse Response, string FilePath);
    }
}
